package com.github.cyf.rateLimit.annotation;

import com.github.cyf.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyifan
 * @create 2025-02-05 9:48
 */
@Aspect
@Component
@Slf4j
public class SlidingWindowRateLimitAspect {
    /**
     * 使用 ConcurrentHashMap 保存每个方法的请求时间戳队列
     */
    private final ConcurrentHashMap<String, ConcurrentLinkedQueue<Long>> REQUEST_TIME_MAP = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.github.cyf.rateLimit.annotation.SlidingWindowRateLimit)")
    private void pointCut() {
    }

    @Around("pointCut()")
    public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SlidingWindowRateLimit slidingWindowRateLimit = method.getAnnotation(SlidingWindowRateLimit.class);

        int maxRequests = slidingWindowRateLimit.requests();
        int timeWindow = slidingWindowRateLimit.timeWindow();

        long currentTime = System.currentTimeMillis();
        // 窗口开始时间
        long thresholdTime = currentTime - TimeUnit.SECONDS.toMillis(timeWindow);
        ConcurrentLinkedQueue<Long> requestTimes = REQUEST_TIME_MAP.computeIfAbsent(method.toString(), k -> new ConcurrentLinkedQueue<>());
        // 这一段代码是滑动窗口限流算法中的关键部分，其功能是移除当前滑动窗口之前的请求时间戳。这样做是为了确保窗口内只保留最近时间段内的请求记录。
        while (!requestTimes.isEmpty() && requestTimes.peek() < thresholdTime) {
            requestTimes.poll();
        }

        // 检查当前时间窗口内的请求次数是否超过限制
        if (requestTimes.size() >= maxRequests) {
            throw new BizException("请求过于频繁，请稍后重试");
        }
        requestTimes.add(currentTime);
        return joinPoint.proceed();
    }
}
